<template>
  <div class="pushAdd">
    <div @click="$router.go(-1)">返回</div>
    <div class="header">
      <div class="icon">
        <img src="../../images/center/ts_naozhong.png"
             alt="">
      </div>
      <div class="text"
           @click="show = true">
        <p>
          <span v-if="date">{{date}}</span>
          <span>{{text}}</span>
          <span v-if="time">{{time}}</span>
        </p>
      </div>
    </div>
    <div class="main">
      <div class="content">
        <!-- 图片 -->
        <template v-if='imgList'>
          <div v-for="(item,i) in imgList"
               :key="i"
               class="imgList">
            <img :src="item.file_path "
                 @click="preview(i)"
                 ref="imgs"
                 class="changeimg"
                 @touchstart="showDeleteButton(i,'img')"
                 @touchend="emptyTime" />
            <van-icon name="close"
                      color='#f00'
                      @click="delData(i,'img')"
                      class="delIcon"
                      v-show="isShowIcon==i" />
          </div>
        </template>
        <!-- 录音 -->
        <div class="recording_box"
             v-if="isRecording">
          <div class="recording">
            <div class="circle"
                 :class="{end:rText == '录音结束'}"></div>
            <p>{{rText}}</p>
            <p>{{addTime}}</p>
          </div>
        </div>
        <!-- 音频 -->
        <template v-if="audioList">
          <div class="customStyle"
               v-for="(item,i) in audioList"
               :key="i+2"
               @click="isShowAudio = -1"
               @touchstart="showDeleteButton(i,'audio')"
               @touchend="emptyTime">
            <div class="icons"
                 @click.stop="changePlay(item,i)">
              <van-icon name="play-circle-o"
                        size="1.5rem"
                        color="#1f8bf8"
                        v-show="!item.isPlay" />
              <van-icon name="pause-circle-o"
                        size="1.5rem"
                        color="#1f8bf8"
                        v-show="item.isPlay" />
            </div>
            <p class="duration">{{item.duration}}</p>
            <div class="progress">
              <van-slider v-model="item.progress"
                          @change="audioEvent(item,i,'progress')"
                          active-color="#1f8bf8">
                <div slot="button"
                     class="progress_btn">
                </div>
              </van-slider>
            </div>
            <p class="total">{{item.total}}</p>
            <van-icon name="close"
                      color='#f00'
                      @click.stop="delData(i,'audio')"
                      class="delAudio"
                      v-show="isShowAudio==i" />
            <audio :src="item.path"
                   ref='audio'
                   @error="audioEvent(item,i,'err')"
                   @ended="audioEvent(item,i,'end')"
                   @timeupdate="audioEvent(item,i,'update')"
                   @durationchange="audioEvent(item,i,'change')"></audio>
            <van-loading type="spinner"
                         v-show="isLoading==i"
                         color="#1f8bf8" />
          </div>
        </template>
        <!-- 文本 -->
        <van-field v-model="message"
                   class="info"
                   autosize
                   type="textarea"
                   placeholder="说点什么吧..." />
      </div>
    </div>
    <div class="footer">
      <div v-for="(item,i) in iconList"
           :key="i"
           class="imgs"
           @click="changeFun(i)">
        <img :src="item.url">
      </div>
      <div class="btn"
           @click="preserve">
        <span>保存</span>
      </div>
    </div>
    <!-- 弹窗 -->
    <van-dialog v-model="show"
                title="循环日期"
                show-cancel-button
                @confirm='confirm'>
      <van-radio-group v-model="radio">
        <van-cell-group>
          <template v-for="(item) in optionList">
            <van-cell :title="item.title"
                      clickable
                      @click="radio = item.id"
                      :key="item.id">
              <van-radio slot="right-icon"
                         :name="item.id" />
            </van-cell>
          </template>
        </van-cell-group>
      </van-radio-group>
    </van-dialog>
    <!-- 显示周 -->
    <van-dialog v-model="showWeek"
                title="循环日期"
                show-cancel-button
                @confirm='confirmWeek'>
      <van-checkbox-group v-model="result">
        <van-cell-group>
          <van-cell v-for="(item, index) in resultList"
                    clickable
                    :key="item.id"
                    :title="`周${item.title}`"
                    @click="toggle(index)">
            <van-checkbox :name="index"
                          ref="checkboxes"
                          slot="right-icon" />
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </van-dialog>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex';

export default {
  name: 'PushAdd',
  components: {},
  data () {
    return {
      iconList: [
        {
          url: require('../../images/center/ts_img.png')
        },
        {
          url: require('../../images/center/ts_mkf.png')
        },
        {
          url: require('../../images/center/ts_pz.png')
        }
      ],
      imgList: [], // 图片列表
      audioList: [],// 音频列表
      text: '提醒时间',
      time: '',   // 分秒
      date: '',   // 日期
      message: '', // 文本域
      show: false, // 控制弹窗
      showWeek: false, // 周
      radio: '1',
      result: [],
      optionList: [
        { title: '周一至周五', id: '1' },
        { title: '每天', id: '2' },
        { title: '一次', id: '3' },
        { title: '自定义', id: '4' },
      ],
      resultList: [
        { title: '一', id: 1 },
        { title: '二', id: 2 },
        { title: '三', id: 3 },
        { title: '四', id: 4 },
        { title: '五', id: 5 },
        { title: '六', id: 6 },
        { title: '日', id: 7 },
      ],
      localId: '', // 图片路径
      recordingId: '', // 录音
      aduioId: '', // 返回下载的音频id
      isRecording: false, // 控制录音
      isClick: true, // 控制多次点击
      serverId: "", // 返回音频的服务器端ID
      addTime: '00.00',// 录音时长
      timer: "", // 录音计时器
      rText: "开始录音",
      timeType: "", // 时间模式
      timeWeek: '', // 循环日期
      isShowIcon: -1, // 控制图片删除图标
      isShowAudio: -1, // 音频的删除图标
      loop: null, // 长按定时器
      num: '', // 区分编辑和新增，1为编辑
      millisecond: 0,
      isSave: false, // 判断是否删除上传到七牛的音频
      isLoading: -1, // 遮罩层
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'turing', 'pushList'])
  },
  watch: {},
  destroyed () {
    // if (!this.isSave) {
    //   // console.log('未保存')
    //   this.audioList.map(val => {
    //     this.delAudioFile(val.path)
    //   })
    // } else {
    //   // console.log('已保存')
    // }
  },
  methods: {

    // 底部功能
    changeFun (i) {
      switch (i) {
        case 0:
          // console.log('相册')
          this.checkPicType(1)
          break;
        case 1:
          // console.log('录音')
          if (this.isClick) {
            this.startRecording()
          }
          break;
        case 2:
          // console.log('拍照')
          this.checkPicType(2)
          break;
      }
    },
    // 相册和相机
    checkPicType (type) {
      let _this = this;
      let sourceType = ["album", "camera"][type - 1];
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: [sourceType], // 可以指定来源是相册还是相机，默认二者都有
        success (res) {
          _this.getFileUrl(res.localIds[0]).then(url => {
            _this.localId = url;
            _this.imgList.push({ type: 3, file_path: url, name: '图片', isAdd: true })
          }).catch(err => {
            _this.$toast.fail(err.msg)
          });
        }
      });
      this.setAvatar = false;
    },
    // 上传文件
    uploadQN (file) {
      return this.http.upload("opening/upload.qupload", {
        token: "FFFX123456",
        file
      });

    },
    // 保存
    preserve () {
      let that = this
      let arr = this.imgList.filter(item => item.isAdd);
      if (arr.length) {
        let i = 0;
        arr.map(e => {
          let file = that.util.base2img(e.file_path);
          that.uploadQN(file)
            .then(r => {
              e.savepath = r.data.savepath;
              i++;
              i >= arr.length && this.subData();
            })
            .catch(err => {
              that.$toast.fail(err.msg)
            });
        });
      } else {
        this.subData();
      }
    },
    // 通过localId获取图片路径(base64)
    getFileUrl (localId) {
      let _this = this;
      return new Promise((res, req) => {
        wx.uploadImage({
          localId, // 图片的localID
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success (data) {
            // let serverId = data.serverId; // 返回图片的服务器端ID
            // 通过serverId获取图片路径
            _this.http.$post("webcat/api/get_image", {
              media_id: data.serverId
            }).then(img => {
              res(img.url);
            }).catch(err => {
              _this.$toast.fail(err.msg)
            });
          }
        });
      });
    },
    // 开始录音
    startRecording () {
      let that = this
      if (!that.isRecording) {
        that.rText = '开始录音'
        wx.startRecord();
        let s = new Date();
        that.isRecording = true
        if (that.isRecording) {
          that.timer = setInterval(() => {
            that.millisecond = new Date() - s
            that.addTime = that.util.numberToTime(that.millisecond, 'mm:ss')
            that.new_time = that.addTime
            if (that.millisecond >= 60000) {
              that.$toast('最多只能录制一分钟')
              that.stopRecording()
            }
          }, 1000)
        }
      } else {
        if (that.millisecond > 1000) {
          that.stopRecording()
        } else {
          that.$toast('录音时间不能少于1秒')
        }
      }
    },
    // 结束录音
    stopRecording () {
      let that = this
      that.isClick = false
      clearInterval(that.timer)
      that.rText = '录音结束'
      setTimeout(() => {
        that.isRecording = false
        that.addTime = '00.00'
        that.isClick = true
        that.millisecond = 0
      }, 1000)
      wx.stopRecord({
        success: function (res) {
          that.recordingId = res.localId;
          that.wxUpload()
        },
        fail: function (err) {
          that.$toast.fail("录音失败");
        }
      });
    },
    // 上传语音到微信服务器
    wxUpload () {
      let that = this
      wx.uploadVoice({
        localId: that.recordingId, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: res => {
          that.serverId = res.serverId; // 返回音频的服务器端ID
          // 请求 
          that.http.$post('webcat/api/get_image', {
            media_id: res.serverId,
            type: 2
          }).then(r => {
            that.audioList.push({
              type: 2,
              path: r.url,
              shortUrl: r.short_url,
              isPlay: false,
              progress: 0,
              total: '00.00',
              duration: '00.00'
            })
            that.isLoading = that.audioList.length - 1
          })
        }
      });
    },
    // 点击播放或在暂停
    changePlay (item, i) {
      // item.isPlay = !item.isPlay
      if (!item.isPlay) {
        this.$refs.audio.map((val, index) => {
          i == index ? val.play() : val.pause()
        })
        this.audioList.map((val, index) => {
          val.isPlay = i == index ? true : false
        })
        item.isPlay = true
      } else {
        this.$refs.audio[i].pause()
        item.isPlay = false
      }
    },
    // 不保存时删除音频文件
    delAudioFile (file) {
      this.http.$post('opening/upload.Qupload/del_file', {
        inputKey: file,
        inputBucket: 'iexue'
      }).then(res => {
        // console.log('删除成功')
      })
    },
    // 音频事件
    audioEvent (item, i, val) {
      let audio = this.$refs.audio[i];
      let a_duration = this.util.numberToTime(audio.duration * 1000 || 0, 'mm:ss');
      let a_currentTime = this.util.numberToTime(audio.currentTime * 1000 || 0, 'mm:ss');
      let progress = parseInt(audio.currentTime / audio.duration * 100);
      if (val == 'change') {
        // 已加载时触发
        item.total = a_duration
        item.duration = a_currentTime
        item.progress = progress
        this.isLoading = -1
      } else if (val == 'update') {
        // 播放位置更新
        item.duration = a_currentTime
        item.progress = progress
      } else if (val == 'end') {
        // 播放结束
        setTimeout(() => {
          item.isPlay = false
          item.duration = '00.00'
          item.progress = 0
        }, 500)
      } else if (val == 'progress') {
        // 拖动进度条
        audio.currentTime = item.progress * audio.duration / 100
      } else {
        // 播放错误
        setTimeout(() => {
          item.path += '&' + new Date().getTime()
        }, 1000);
      }
    },
    // 点击图标删除列表数据
    delData (i, val) {
      if (val == 'img') {
        this.$dialog.confirm({
          message: '是否删除这张图片？'
        }).then(() => {
          this.imgList.splice(i, 1)
          this.isShowIcon = -1
          this.$toast.success('删除成功')
        }).catch(() => {
          this.isShowIcon = -1
        });
      } else {
        this.$dialog.confirm({
          message: '是否删除这条语音？'
        }).then(() => {
          this.audioList.splice(i, 1)
          this.isShowAudio = -1
          this.$toast.success('删除成功')
          // this.delAudioFile(this.audioList[i].path)
        }).catch(() => {
          this.isShowAudio = -1
        });
      }

    },
    // 提交数据
    subData () {
      let contentList = [];
      if (this.message) {
        contentList.push({ type: 1, name: this.message })
      }
      this.imgList.map(val => {
        contentList.push({ type: 3, path: val.savepath, name: '图片' })
      })
      this.audioList.map(val => {
        contentList.push({ type: 2, path: val.shortUrl, name: '音频', duration: val.total })
      })
      if (this.num == 1) {
        if (this.isLoading == '-1') {
          let editParams = {
            msg_id: this.pushList.msg_id,
            time_type: this.timeType,
            time_week: JSON.stringify(this.time_week),
            time_push: this.timeType == 1 ? (this.date + ' ' + this.time) : this.time,
            content: JSON.stringify(contentList)
          }
          this.http.$post('robot/message.api/edit', editParams).then(res => {
            this.isSave = true
            this.$toast.success('编辑成功')
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500)
          }).catch(err => {
            this.$toast.fail(err.msg)
          })
        } else {
          this.$toast('请稍等')
        }
      }
      else {
        if (this.isLoading == '-1') {
          let addParams = {
            push_uid: this.turing.app_id,
            receive_uid: this.userInfo.uid,
            time_type: this.timeType,
            time_week: JSON.stringify(this.timeWeek),
            time_push: this.timeType == 1 ? (this.date + ' ' + this.time) : this.time,
            content: JSON.stringify(contentList)
          }
          this.http.$post('robot/message.api/add', addParams).then(res => {
            this.$toast.success('保存成功')
            this.isSave = true
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500)

          }).catch(err => {
            this.$toast.fail(err.msg)
          })
        } else {
          this.$toast('请稍等')
        }
      }

    },
    // 确认
    confirm () {
      switch (this.radio) {
        case '1':
          this.timeType = 2
          this.timeWeek = [1, 2, 3, 4, 5]
          this.util.picker({
            type: "time",
            title: "选择时间",
            maxHour: '0',
            minHour: '23',
            sure: this.checkTime,
          });
          break;
        case '2':
          this.timeType = 2
          this.timeWeek = [1, 2, 3, 4, 5, 6, 7]
          this.util.picker({
            type: "time",
            title: "选择时间",
            maxHour: '0',
            minHour: '23',
            sure: this.checkTime,
          });
          break;
        case '3':
          this.timeType = 1
          this.util.picker({
            type: "date",
            title: "选择日期",
            dfValue: new Date(),
            maxDate: new Date('2050-1-1'),
            minDate: new Date("2000-1-1"),
            sure: this.checkDate,
            formatter: this.formatters
          });
          break;
        case '4':
          this.timeType = 2
          this.showWeek = true
          break;
      }
    },
    // 选择时间的值
    checkTime (val) {
      switch (this.radio) {
        case '1':
        case '2':
          this.date = ''
          this.text = this.optionList[this.radio - 1].title
          break;
        case '4':
          this.date = ''
          let arr = this.result
          let str = arr.sort().map(val => {
            return this.resultList[val].title
          })
          let str_id = arr.sort().map(val => {
            return this.resultList[val].id
          })
          this.timeWeek = str_id
          this.text = '周' + str
          break;
      }
      this.time = val
    },
    // 选择年月日
    checkDate (val) {
      if (val) {
        let date = this.util.formatTime(val, "Y-MM-DD");
        this.date = date
        // 根据日期转化星期
        let arys1 = date.split('-')
        let ssdate = new Date(arys1[0], parseInt(arys1[1] - 1), arys1[2]);
        let week1 = String(ssdate.getDay()).replace("0", "日").replace("1", "一").replace("2", "二").replace("3", "三").replace("4", "四").replace("5", "五").replace("6", "六")//就是你要的星期几
        let week = "周" + week1 //就是你要的星期几
        switch (week1) {
          case '一':
            this.timeWeek = [1]
            break;
          case '二':
            this.timeWeek = [2]
            break;
          case '三':
            this.timeWeek = [3]
            break;
          case '四':
            this.timeWeek = [4]
            break;
          case '五':
            this.timeWeek = [5]
            break;
          case '六':
            this.timeWeek = [6]
            break;
          case '日':
            this.timeWeek = [7]
            break;
        }
        this.text = week
        this.util.picker({
          type: "time",
          title: "选择时间",
          maxHour: '0',
          minHour: '23',
          sure: this.checkTime,
        });
      }
    },
    // 复选框
    toggle (index) {
      this.$refs.checkboxes[index].toggle();
    },
    // 确定星期几
    confirmWeek () {
      if (this.result) {
        this.util.picker({
          type: "time",
          title: "选择时间",
          maxHour: '0',
          minHour: '23',
          sure: this.checkTime,
        });
      }
    },
    // 点击预览
    preview (i) {
      this.isShowIcon = -1
      let arr = []
      this.$refs.imgs.map(val => {
        arr.push(val.src)
      })
      wx.previewImage({
        current: this.$refs.imgs[i].src, // 当前显示图片的http链接
        urls: arr // 需要预览的图片http链接列表
      });
    },
    // 长按事件
    showDeleteButton (e, val) {
      clearTimeout(this.loop); //再次清空定时器，防止重复注册定时器
      this.loop = setTimeout(function () {
        if (val == 'img') {
          this.isShowIcon = e
        } else {
          this.isShowAudio = e
        }
      }.bind(this), 1500);
    },
    //清空
    emptyTime () {
      clearTimeout(this.loop); //清空定时器，防止重复注册定时器
    },
  },
  created () {
    this.util.setWxConfig([
      'chooseImage',
      'uploadImage',
      'startRecord',
      'stopRecord',
      'uploadVoice',
      'previewImage',
    ]).catch(this.$err);
    // console.log(this.pushList, this.$route.query.num)
    let pushList = this.pushList;
    if (this.$route.query.num) {
      this.num = this.$route.query.num
      let dateList = pushList.push_date.split(' ')
      if (pushList.time_type == 1) {
        this.date = dateList[0]
        this.text = dateList[1]
        this.time = dateList[2]
      } else {
        if (JSON.stringify(pushList.time_week) == JSON.stringify([1, 2, 3, 4, 5])) {
          this.text = '周一至周五'
        } else if (JSON.stringify(pushList.time_week) == JSON.stringify([1, 2, 3, 4, 5, 6, 7])) {
          this.text = '每天'
        } else {
          this.text = dateList[0]
        }
        this.time = dateList[1]
      }
      this.timeType = pushList.time_type
      this.time_week = pushList.time_week
      pushList.content.map(val => {
        if (val.type == 1) {
          this.message = val.name
        } else if (val.type == 3) {
          this.imgList.push({ type: 3, file_path: val.file_path, savepath: val.path, name: "图片" })
        } else {
          this.audioList.push({ type: 2, path: val.file_path, shortUrl: val.path, total: val.duration, isPlay: false, progress: 0, duration: '00.00' })
        }
      })
    } else {
      this.num = ''
    }

  },
  mounted () {
  },
}
</script>
<style lang='less' scoped>
* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.header {
  width: 100%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 1rem;
  .icon {
    width: 1rem;
    height: 1rem;
    img {
      width: 100%;
    }
  }
  .text {
    padding-top: 0.1rem;
    p {
      font-size: 0.8rem;
      color: #999999;
      position: relative;
      &::after {
        content: "";
        display: block;
        position: absolute;
        top: 0.4rem;
        right: -1.5rem;
        width: 0;
        height: 0;
        border-top: 0.4rem solid #c4c4c4;
        border-right: 0.4rem solid transparent;
        border-left: 0.4rem solid transparent;
      }
      span {
        padding-left: 0.5rem;
      }
    }
  }
}
.main {
  margin-bottom: 3.5rem;
  padding: 0 1rem;
  box-sizing: border-box;
  max-height: 100%;
  .content {
    width: 100%;
    background-color: #fff;
    .info {
      padding: 1rem 0 2rem 1rem;
      font-size: 1rem;
      color: #999999;
    }
    .imgList {
      display: inline-block;
      padding: 0.5rem;
      max-width: 100%;
      max-height: 100%;
      position: relative;
      .changeimg {
        max-width: 100%;
        max-height: 100%;
      }
      .delIcon {
        position: absolute;
        top: 1rem;
        right: 1rem;
      }
    }
    .audioList {
      margin: 1rem;
      audio {
        width: 90%;
        height: 1.5rem;
      }
    }
    .recording_box {
      padding: 1rem;
      .recording {
        width: 80%;
        height: 3rem;
        border: 1px dashed #999;
        display: flex;
        align-items: center;
        .circle {
          width: 0.5rem;
          height: 0.5rem;
          border-radius: 50%;
          background-color: #f00;
          margin-left: 2rem;
        }
        .end {
          background-color: skyblue;
        }
        p {
          padding-left: 1rem;
          font-size: 1rem;
        }
      }
    }

    .customStyle {
      padding: 1rem 1rem 0 1rem;
      height: 1.5rem;
      display: flex;
      align-items: center;
      position: relative;
      .icons {
        padding-top: 0.3rem;
      }
      .duration {
        padding: 0 0.5rem;
      }
      .progress {
        width: 10rem;
        padding-right: 0.5rem;
        .progress_btn {
          width: 0.5rem;
          height: 0.5rem;
          border-radius: 50%;
          background: #1f8bf8;
        }
      }
      .delAudio {
        padding-left: 0.5rem;
      }
      .van-loading {
        position: absolute;
        top: 35%;
        left: 0;
        width: 100%;
        text-align: center;
        background: rgba(0, 0, 0, 0.1);
      }
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 3rem;
  background-color: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .imgs {
    width: 2rem;
    height: 2rem;
    overflow: hidden;
    padding-top: 0.5rem;
    img {
      width: 100%;
    }
  }
  .btn {
    width: 6rem;
    height: 2rem;
    background-color: #1f8bf8;
    border-radius: 1rem;
    text-align: center;
    span {
      line-height: 2rem;
      font-size: 1rem;
      letter-spacing: 0.1rem;
      color: #ffffff;
    }
  }
}
</style>